package cn.jinjimi.app.main.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView;

import com.facebook.drawee.backends.pipeline.Fresco;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.app.entity.LinkBean;
import cn.jinjimi.app.entity.Notice;
import cn.jinjimi.app.main.HomePresenter;
import cn.jinjimi.app.main.adapter.recycler.HomeAdapter;
import cn.jinjimi.app.main.extend.BaseNetControlFragment;
import cn.jinjimi.app.main.widget.biz.HomeBannerView;
import cn.jinjimi.app.main.widget.biz.HomeEntranceView;
import cn.jinjimi.app.main.widget.biz.HomeHeadView;
import cn.jinjimi.app.main.widget.biz.HomeStatusView;
import cn.jinjimi.app.main.widget.biz.HomeNoticesView;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;
import cn.jinjimi.app.ui.GridDividerDecoration;
import cn.jinjimi.domain.data.dto.CommentList;
import cn.jinjimi.domain.data.dto.ConfigDTO;
import cn.jinjimi.domain.entity.ProductList;
import cn.jinjimi.framework.router.Router;

/**
 * 首页推荐
 */
public class FirstTabFragment extends BaseNetControlFragment implements HomePresenter.IViewController,
        HomeStatusView.onActionClickListener {

    private XRecyclerView mRecyclerView;
    private HomeAdapter mAdapter;

    private HomeHeadView mHomeHeadView;
    private HomeEntranceView mHomeEntranceView;
    private HomeBannerView mHomeBannerView;

    private HomePresenter mPresenter;
    private AtomicBoolean isRefreshing = new AtomicBoolean(false);
    private HomeNoticesView mNewsView;

    @Override
    protected int getBizLayoutResourceId() {
        return R.layout.fragment_home_layout;
    }

    @Override
    protected void initialBiz() {

    }

    @Override
    protected void initial() {
        super.initial();
        initView();
        initListener();
        initData();
    }

    private void initView() {
        mRecyclerView = (XRecyclerView) findView().findViewById(R.id.recyclerview);
        mRecyclerView.setNoMore(true);
        mRecyclerView.setFooterWithText("");
        mRecyclerView.setFootViewHeight(getResources().getDimensionPixelOffset(R.dimen.dp_25));
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 6));
        mRecyclerView.addItemDecoration(new GridDividerDecoration(getActivity()));
        mAdapter = new HomeAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setPullRefreshEnabled(true);
        // 广告
        mHomeHeadView = new HomeHeadView(getActivity());
        mRecyclerView.addHeaderView(mHomeHeadView);
        // 头条
        mNewsView = new HomeNoticesView(getActivity());
        mRecyclerView.addHeaderView(mNewsView);
        // 快捷入口
        mHomeEntranceView = new HomeEntranceView(getActivity());
        mRecyclerView.addHeaderView(mHomeEntranceView);
        // banner
        mHomeBannerView = new HomeBannerView(getActivity());
        mHomeBannerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Router.create(getContext(), "jjm://main/index?position=2").open();
            }
        });
        mRecyclerView.addHeaderView(mHomeBannerView);
    }

    private void initListener() {
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData();
            }

            @Override
            public void onLoadMore() {
                onLoadComplete();
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        Fresco.getImagePipeline().resume();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        Fresco.getImagePipeline().pause();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        break;
                    default:break;
                }
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void initData() {
        mPresenter = new HomePresenter(this);
    }

    @Override
    protected void loadData() {
        if (findView() != null && !isRefreshing.get()) {
            isRefreshing.set(true);
            if (mPresenter != null) {
                mPresenter.reloadAll();
            }
        }
    }

    public void refreshComplete() {
        if (mRecyclerView != null && isRefreshing.get()) {
            isRefreshing.set(false);
            mRecyclerView.refreshComplete();
        }
    }

    public void onLoadComplete() {
        if (mRecyclerView != null) {
            mRecyclerView.loadMoreComplete();
        }
    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent event) {
        loadData();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint() && checkRefresh()) {
            return;
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 检查距离上次刷新是否大于10分钟
     */
    private boolean checkRefresh() {
        if (mRecyclerView != null) {
            if (System.currentTimeMillis() - mRecyclerView.getRefreshTime() > Constants.MIN_10) {
                loadData();
                return true;
            }
        }
        return false;
    }

    @Override
    public void onRefreshClick() {

    }

    @Override
    public void renderCateList(List<ProductList> list) {
        if (mAdapter != null) {
            mAdapter.setCateData(list);
        }
    }

    @Override
    public void renderAdvs(List<LinkBean> advs) {
        if (mHomeHeadView != null && advs != null) {
            mHomeHeadView.setAdvData(advs);
        }
    }

    @Override
    public void renderEntrance(List<LinkBean> entrances) {
        if (entrances == null || entrances.size() == 0) {
            mHomeEntranceView.setVisibility(View.GONE);
            return;
        }
        if (mHomeEntranceView != null) {
            mHomeEntranceView.setVisibility(View.VISIBLE);
            mHomeEntranceView.setData(entrances);
        }
    }

    @Override
    public void renderComments(CommentList comments) {
        if (mAdapter != null) {
            mAdapter.setCommentData(comments);
        }
    }

    @Override
    public void renderGoods(ProductList list) {
        if (mAdapter != null) {
            mAdapter.setGoodsData(list);
        }
    }

    @Override
    public void onLoading() {
        netLoadingData();
    }

    @Override
    public void onLoaded(int res) {
        if (Constants.Code.RES_SUCCESS == res) {
            netLoadSucc();
        } else if (Constants.Code.RES_ERROR == res) {
            netLoadError();
        }
        refreshComplete();
    }

    @Override
    public void renderNotices(List<Notice> data) {
        if (mNewsView != null) {
            mNewsView.render(data);
        }
    }

    @Override
    public void renderLimit(ConfigDTO.LimitEntry limit) {
        if (limit != null) {
            mHomeEntranceView.setData(limit);
        }
    }

    @Override
    public void renderRecommends(List<Notice> data) {
        if (data != null && mAdapter != null) {
            mAdapter.setRecommends(data);
        }
    }

}
